<template>
  <div class="login-container">
    <el-form
      v-if="loginFlag"
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">
          {{ $t('login.title') }}
        </h3>
        <lang-select class="set-language" />
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model.trim="loginForm.username"
          :placeholder="$t('login.username')"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="off"
        />
      </el-form-item>

      <el-tooltip
        v-model="capsTooltip"
        content="Caps lock is On"
        placement="right"
        manual
      >
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model.trim="loginForm.password"
            :type="passwordType"
            :placeholder="$t('login.password')"
            name="password"
            tabindex="2"
            autocomplete="off"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>
      <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
        {{ $t('login.logIn') }}
      </el-button>
      <p class="forget-password"><span @click.stop.prevent="handlePasswordReset">{{ $t('login.forget_password') }}?</span></p>
    </el-form>

    <PasswordReset
      v-else
      :is-login="true"
      class="login-form"
      @on-password-reset="loginFlag = true"
      @on-submit-success="loginFlag = true"
    />

    <el-dialog
      title="选择用户"
      :close-on-click-modal="false"
      :width="muliteAccountList.length>2 ? '800px' : '545px'"
      :visible.sync="showDialog"
    >
      <div>
        <el-tag type="danger" size="medium"><i class="el-icon-warning" />&nbsp;当前登录账号存在多个，请选择本人账号登录。</el-tag>
        <el-tag size="medium"><i class="el-icon-info" />&nbsp;tips：可以使用手机号码登录</el-tag>
      </div>
      <div class="user-list-box margin-top-12">
        <el-card
          v-for="item in muliteAccountList"
          :key="item.id"
          shadow="hover"
          class="box-card"
        >
          <div slot="header" class="user-header">
            <span>{{ item.realName }}</span>
            <el-button :loading="item.loading" type="text" @click="selectToLogin(item)">登录</el-button>
          </div>
          <div class="text-item">
            <p><label>登陆账号：</label><span>{{ item.loginName }}</span></p>
            <p><label>用户名称：</label><span>{{ item.username }}</span></p>
            <p><label>电话号码：</label><span>{{ item.telephoneNumber || '暂无电话' }}</span></p>
          </div>
        </el-card>
      </div>
      <!-- <social-sign /> -->
    </el-dialog>

  </div>
</template>

<script>
import LangSelect from '@/components/LangSelect'
// import SocialSign from './components/SocialSignin'
import PasswordReset from '@/components/PasswordReset'

import { getUserAccountsList } from '@/api/user'

export default {
  name: 'Login',
  components: {
    LangSelect,
    // SocialSign,
    PasswordReset
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入账号！'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码！'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        client_id: process.env.VUE_APP_client_id,
        client_secret: process.env.VUE_APP_client_secret,
        grant_type: 'password'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      loginFlag: true,
      muliteAccountList: []
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    },
    loginFlag: {
      handler(v) {
        if (v) {
          this.$nextTick(() => {
            this.loginForm.username = ''
            this.loginForm.password = ''
            this.$refs.loginForm.clearValidate()
          })
        }
      }
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm && this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            const { username: loginName } = this.loginForm
            const res = await getUserAccountsList({ loginName })
            if (res.data.length > 1) {
              this.showDialog = true
              this.muliteAccountList = res.data
              return
            }
            await this.$store.dispatch('user/login', this.loginForm)
            this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
          } catch (error) {
            console.error(error)
          } finally {
            this.loading = false
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    handlePasswordReset() {
      this.loginFlag = !this.loginFlag
    },
    async selectToLogin(params) {
      try {
        this.$set(params, 'loading', true)
        const form = JSON.parse(JSON.stringify(this.loginForm))
        form.username = params.username
        await this.$store.dispatch('user/login', form)
        this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
      } catch (error) {
        console.error(error)
      } finally {
        this.$set(params, 'loading', false)
      }
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss">
  $bg:#283443;
  $light_gray:#fff;
  $cursor: #fff;
  $text: #515a6e;
  @supports (-webkit-mask: none) and (not (cater-color: $text)) {
    .login-container .el-input input {
      color: $text;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-form-item--medium .el-form-item__content{
      line-height: 30px;
    }
    .el-button--medium{
      padding: 15px 20px;
      margin-bottom: 20px;
    }
    .verify-btn{
      margin-bottom: 0;
      float: right;
    }
    .el-input {
      display: inline-block;
      height: 30px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $text;
        height: 30px;
        caret-color: $text;
        line-height: 30px;
        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px #fff inset !important;
          -webkit-text-fill-color: #515a6e !important;
        }
        &::-webkit-credentials-auto-fill-button {
          display: none !important;
          visibility: hidden;
          pointer-events: none;
          position: absolute; /* 避免占用 input 元素额外的 padding，正常情况下存在 display: none!; 就可以了 */
          right: 0;
        }
      }
    }

    .el-form-item {
      border: 1px solid #dcdee2;
      background: #fff;
      border-radius: 5px;
      color: #515a6e;
    }
  .el-dialog__body{
    padding-bottom: 35px;
  }
  .user-list-box {
    display: flex;
    justify-content: flex-start;
    flex-flow: wrap;
    border: 1px solid #F5F5F5;
    max-height: 370px;
    overflow-y: scroll;
    .box-card{
      width: 220px;
      margin: 15px;
      cursor: pointer;
      background: #FAFAFA;
    }
    .el-card__header,
    .el-card__body{
      padding: 5px 15px;
    }
    .user-header{
      padding: 8px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .el-button{
        float: right;
        padding: 3px 0px;
        margin-bottom: 0;
      }
      &>span{
        color: #212121;
        font-weight: 500;
      }
    }
    .text-item{
      p{
        line-height: 2;
        margin: 0;
      }
      label{
        line-height: 1;
        font-weight: 500;
        color: #424242;
      }
      span{
        color: #616161;
      }
    }
  }
  }
</style>

<style lang="scss" scoped>
  $bg:#2d3a4b;
  $dark_gray:#889aa4;
  $light_gray:#eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-image: url("../../assets/login.jpg");
    background-repeat: no-repeat;
    background-position: center center;
    overflow: hidden;
    background-size: cover;
    position: relative;
    .login-form {
      position: relative;
      width: 400px;
      max-width: 100%;
      padding: 40px 35px 0;
      margin-top: 130px;
      margin-left: calc(100% - 520px);
      overflow: hidden;
      background-color: #fff;
      border-radius: 5px;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color:#515a6e;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 20px;
        color: #17233d;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }

      .set-language {
        color: #515a6e;
        position: absolute;
        top: 3px;
        font-size: 18px;
        right: 0px;
        cursor: pointer;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
    .forget-password{
      font-size: 14px;
      text-align: right;
      margin-bottom: 20px;
      margin-top: 0;
      span{
        cursor: pointer;
        color: $dark_gray;
        &:hover{
          color: #1890ff;
        }
      }
    }
  }
</style>
